// subPages/health/pressure/pressure.js
import * as echarts from '../../../ec-canvas/echarts';
var util =  require('../../../utils/util.js');
var navListJson = require('../../../data/navListJson');
var indexJson = require('../../../data/indexJson');
var recordJson = require('../../../data/recordJson');
let LineChart = null
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    ec: {
      // lazyLoad: true // 延迟加载
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setDate()
  },

  bindDateChange: function(e) {
    var that = this
    that.setData({
      date: e.detail.value,
    })
    that.getData(that.data.date)
  },

  //设置日期
  setDate:function(){
    var that = this
    let date = util.setTime10(new Date())
    let createtime = util.setTime(new Date())
    let Y = date.split('-')
    that.setData({
      createtime: createtime,
      date: date,
      dateStart: Y[0]- 3,
      dateEnd: date,
      thList: navListJson.pressureThList
    })
    that.getData(date)
  },
  

  //获得数据
  getData:function(date){
    var that = this
    wx.request({
        url: app.globalData.apiUrl +'/get_user_xueya',
        data: {
          userid: app.globalData.userId,
          time: date
        },
        method: 'get',
        header: {
          'content-type': 'application/json' //默认值
        },
        success: function (res) {
          // console.log(res)
          if(res.data.code == '200'){
            that.processingOneData(res.data.data);
            that.processingEchartData(res.data.data2);            
            that.processingData(res.data.data);
          }else{
            util.showModal('提示','数据异常')
            return;
          }
        },
        fail: function (res) {
          console.log("失败",res);
        }
    })
  },

  //处理最新一条数据
  processingOneData:function(list){
    var that = this
    if(list.length != 0){
      var pressureList = indexJson.pressureList
      for(let i in pressureList)
      {
        switch (pressureList[i].index) {
          case 1:
            pressureList[i].data = list[0].height
            break;
          case 2:
            pressureList[i].data = list[0].low
            break;
          case 3:
            pressureList[i].data = list[0].heart
            break;
        }
      }
      that.setData({
        isData: true,
        createtime: util.setTime9(list[0].createtime),
        dataList: pressureList,
      })
    }else{
      that.setData({
        isData: false,
        dataList: indexJson.pressureList2,
        tipTxt: {
          tipTxt: '暂无测量数据',
          tipImg: '/resources/index/noData.png'
        }
      })
    }
  },

  //处理图表数据
  processingEchartData:function(list){
    if(list.length != 0){
      var that = this
      var heightList = []
      var lowList = []
      var heartList = []
      var echartTime = []
      for(var i in list){
        echartTime.push(list[i].createtime)
        heightList.push(list[i].height)
        lowList.push(list[i].low)
        heartList.push(list[i].heart)
      }
      that.setData({
        heightList: heightList,
        lowList: lowList,
        heartList: heartList,
        echartTime: echartTime
      })
      that.linechartsComponnet = that.selectComponent('#mychartLine');
      LineChart = null
      that.getLineGraphData();  //创建图表
    }
  },

  //处理数据
  processingData:function(list){
    // console.log(list)
    var that = this
    if(list.length != 0){
      for(var i in list){
        var date = util.setTime9(list[i].createtime).substring(8,10)
        var time = list[i].addtime.substring(11,16)
        list[i].createtime = date + '日' + ''  + time
      }
      that.setData({
        isData2: true,
        historyList: list,
      })
    }else{
      that.setData({
        isData2: false,
        tipTxt2: {
          tipTxt2: '暂无测量数据',
          tipImg2: '/resources/index/noDataSmall.png'
        }
      })
    }
  },

  //线图表
  getLineGraphData:function(){
    var that = this
    if (!LineChart){
      that.init_LineEcharts(); //初始化图表
    }else{
      that.setLineOption(); //更新数据
    }
  },

  //初始化图表
  init_LineEcharts: function () {
    var that = this
    that.linechartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      LineChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      LineChart.showLoading({
        text : '正在努力的读取数据中...'
      });
      // Chart.setLineOption(this.getLineOption());
      that.setLineOption();
      // LineChart.dispatchAction({
      //   type: 'highlight',
      //   seriesIndex: 0,
      //   dataIndex: 0
      // });
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return LineChart;
    });
  },

  setLineOption: function () {
    LineChart.clear();  // 清除
    LineChart.setOption(this.getLineOption());  //获取新数据
  },

  //设置折线图表
  getLineOption: function () {
    var that = this
    // 指定图表的配置项和数据
    var option = {
      title : {
        text: '',
        subtext: ''
      },
      grid:{ 
        borderWidth:0,
        x:0,
        y:30,
        x2:0,
        y2:0,
        containLabel: true
      },
      xAxis: { 
        type: 'category',
        show:true,
        boundaryGap:true,
        data : that.data.echartTime,
        axisLine:{
          show:true,
          lineStyle:{
            color: 'white',
            width: 1,
          }
        },
        axisTick:{
          show:false
        },
        axisLabel:{
          show:true,
          color: 'white',
          interval: 0,
          formatter: '{value}',
          formatter:function(value){
            return util.setTime13(value) + '日'
          }
        },
      },
      yAxis: {
        type: 'value',
        boundaryGap:false,
        show:true,
        scale: false,
        splitNumber:2,
        axisLine:{
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine:{
          show:true,
          lineStyle:{
            color: 'rgba(255,255,255,0.3)',
          }
        },
        axisLabel:{
          show: true,
          inside: true,
          verticalAlign: 'bottom',
          margin: 0,
          color: '#76ebdc',
          formatter:function(value,index){
            return value
          }
        },
      },
      dataZoom:[
        {
          show: false,
          type:'slider',
          start: util.dataZoom(that.data.echartTime),
          end: 100,
          left:'3%',
          right:'3%',
          maxValueSpan: 10,
        },
        {
          type: 'inside',
        },
      ],
      series : [{
        name:'高压',
        type:'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 12,
        itemStyle : {
          normal: {
            color: '#fff',
          },
        },
        emphasis:{
          label:{
            show: true,
            position: 'top',
            formatter:function(params){
              return params.data;
            }
          },
          itemStyle:{
            borderWidth: 12,
            borderType:'solid',
            borderColor: 'rgba(255,255,255,0.5)'
          }
        },
        data: that.data.heightList
      },{
        name:'低压',
        type:'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 12,
        itemStyle : {
          normal: {
            color: '#1360fe',
          },
        },
        emphasis:{
          label:{
            show: true,
            position: 'top',
            formatter:function(params){
              return params.data;
            }
          },
          itemStyle:{
            borderWidth: 12,
            borderType:'solid',
            borderColor: 'rgba(19,96,254,0.5)'
          }
        },
        data: that.data.lowList
      },{
        name:'心率',
        type:'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 12,
        itemStyle : {
          normal: {
            color: '#d35757',
          },
        },
        emphasis:{
          label:{
            show: true,
            position: 'top',
            formatter:function(params){
              return params.data;
            }
          },
          itemStyle:{
            borderWidth: 12,
            borderType:'solid',
            borderColor: 'rgba(211,87,87,0.5)'
          }
        },
        data: that.data.heartList
      }]
    };
    LineChart.hideLoading()
    return option;
  },

  //记录按钮
  recordBtn: function (e) {
    // console.log(e);
    var currentStatu = e.currentTarget.dataset.statu;
    this.anim(currentStatu);
  },

  //动画部分
  anim: function (currentStatu) {
    // 第1步：创建动画实例 
    var animation = wx.createAnimation({
      duration: 200,  //动画时长
      timingFunction: "linear", //线性
      delay: 0  //0则不延迟
    });
    
    // 第2步：这个动画实例赋给当前的动画实例
    this.animation = animation;
 
    // 第3步：执行第一组动画：Y轴偏移240px后(盒子高度是400px)，停
    animation.translateY(300).step();
 
    // 第4步：导出动画对象赋给数据对象储存
    this.setData({
      animationData: animation.export()
    })
    
    // 第5步：设置定时器到指定时候后，执行第二组动画
    setTimeout(function () {
      // 执行第二组动画：Y轴不偏移，停
      animation.translateY(0).step()
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
      this.setData({
        animationData: animation
      })
      
      //完成
      if (currentStatu == "complete") {
        this.setData(
          {
            isHeight: false,
          }
        );
      }

      //取消
      else if (currentStatu == "cancel") {
        this.setData(
          {
            isHeight: false,
          }
        );
      }
    }.bind(this), 200)
  
    // 显示抽屉
    if (currentStatu == "open") {
      this.setData(
        {
          isHeight: true,
          title: '记录血压',
          recordList: recordJson.bloodPressure,
        }
      );
    }
  },

  //提交表单
  formSubmit:function(e){
    // console.log(e)
    var that = this
    let height = e.detail.value.height;//高压
    let low = e.detail.value.low;//低压
    let heart = e.detail.value.heart;//心率
    if (height == "" || low == "" || heart == ""){
      util.showModal('提示','请输入完整信息')
      return
    }
    if(height.length > 0)
    {
      let type= 'number'
      let validation = util.validation(height,type)
      if(!validation){
        util.showModal('提示','高压输入不正确')
        return
      }
    }
    if(low.length > 0)
    {
      let type= 'number'
      let validation = util.validation(low,type)
      if(!validation){
        util.showModal('提示','低压输入不正确')
        return
      }
    }
    if(heart.length > 0)
    {
      let type= 'number'
      let validation = util.validation(heart,type)
      if(!validation){
        util.showModal('提示','心率输入不正确')
        return
      }
    }
    that.save(height,low,heart);
  },

  //保存信息
  save:function(height,low,heart){
    var that = this
    wx.request({
      url: app.globalData.apiUrl +'/add_user_xueya', //接口地址
      data: {
        userid: app.globalData.userId,
        height: height,
        low: low,
        heart: heart
      },
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded' //默认值
      },
      success: function (res) {
        // console.log(res)
        if(res.data.code == '200'){
          util.showToast('保存成功','success')
          that.getData(that.data.date);
        }else{
          util.showModal('提示','记录失败')
          return;
        }
      }
    })
  },

  //选择导航栏
  switchNav(event){
    var that = this
    var cur = event.currentTarget.dataset.current;      
    if (that.data.currentTab == cur) {
      return false;
    } else {
      that.setData({
          currentTab: cur
      })
    }
  },

  //阻止穿透
  preventTouchMove: function () {
    // console.log('stop user scroll it!');
    return;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    LineChart = null
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    LineChart = null    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: 'PAPN健康管理',
      path: 'pages/index/index',
      success: function(res) {
        // res.shareTickets 
      },
      fail: function(res) {
          console.log(res)
      }
    }
  }
})